
import Vue from 'vue'
import Vuex from 'vuex'
import cart from './modules/cart'
import profile from './modules/profile'
import {getStorage,setStorage,removeStorage} from '../util/storage'
import {COMMON_SET_LOCATION} from './mutationTypes'
Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'


const defaultState = {
  location:{
    name: "",
    address: '',
    latitude: null, // 当前位置纬度
    longitude: null, // 当前位置经度
    geohash: null
  }
}
console.log('加载store ....');
const location = getStorage('location')
const state = location? {location} : defaultState

const getters = {}
const mutations = {
  [COMMON_SET_LOCATION](state, payload){
    console.log(payload);
    state.location = payload
  }
}
const actions = {
  [COMMON_SET_LOCATION]({commit}, payload){
    // 保存到存储
    setStorage('location', payload)
    // 保存到历史记录
    const historyLocations = getStorage('history_locations')||[]
    const existed = historyLocations.find(item=>{
      return item.geohash === payload.geohash
    })
    if(!existed){
      historyLocations.push(payload)
    }
    setStorage('history_locations',historyLocations)
    commit(COMMON_SET_LOCATION,payload)
  }
}


export default new Vuex.Store({
  // 模块
  modules:{
    cart,
    profile
  },

  // 公共store
  state,
  getters,
  mutations,
  actions,
  // 严格模式，发布时应关闭
  strict: debug
})